<template>
  <div class="mobile-content">
    <Sticky>
      <Collapse v-model="activeNames">
        <CollapseItem title="搜索" name="1" icon="search">
          <CellGroup inset>
            <Field v-model="searchForm.siteName" is-link readonly required name="siteName" label="站点"
              placeholder="点击选择站点" @click="sitePicker = true" />
            <Popup v-model:show="sitePicker" position="bottom">
              <Picker :columns="sitePickerOptions" @confirm="sitePickerConfirm" @cancel="sitePicker = false" />
            </Popup>
            <Field v-model.trim="searchForm.keyword" name="keyword" label="关键字" placeholder="请输入关键字" clearable
              autocomplete="no" />
          </CellGroup>
          <div style="padding: 5px 16px;">
            <Button type="primary" block round @click="onRefresh">
              确 认
            </Button>
          </div>
        </CollapseItem>
      </Collapse>

      <DropdownMenu>
        <DropdownItem v-model="filter.category" :options="categoryFilterOptions" />
      </DropdownMenu>
    </Sticky>
    <PullRefresh v-model="refreshing" @refresh="onRefresh">
      <List v-model:loading="loading" :finished="finished" finished-text="没有更多了" v-model:error="error"
        :error-text="errorText" :immediate-check="false" @load="onLoad">
        <Cell v-for="(item, index) in filterList" :key="item.id" clickable @click="opShowFunc(item)">
          <template #title>
            <div class="row-title">
              <span>{{  index + 1  }}.</span>
              <Tag plain v-if="item.isAdd" type="success">已添加</Tag>
              <span>{{  item.title  }}</span>
            </div>
          </template>
          <template #label>
            <p>{{  item.pubDate  }}</p>
            <Space>
              <Tag type="primary">{{  categoryName(item.category)  }}</Tag>
            </Space>
          </template>
        </Cell>
      </List>
    </PullRefresh>
    <ActionSheet v-model:show="opShow" :actions="actions" cancel-text="取消" close-on-click-action @select="onSelect" />

    <ActionSheet v-model:show="addShow" title="添加种子">
      <AddTorrent ref="addTorrent" @close="() => { addShow = false; onRefresh(); }" />
    </ActionSheet>
  </div>
</template>

<script name="rss-mobile" setup>
import { Sticky, Field, Popup, Picker, Collapse, CollapseItem, DropdownMenu, DropdownItem, Notify, PullRefresh, List, Cell, CellGroup, Space, Tag, ActionSheet, Button } from 'vant';
import { reactive, ref, watchEffect, nextTick } from 'vue';

import AddTorrent from '@/mobile/Torrent/Add.vue';

import BaseApi from '@/api/api.js'
import SearchApi from '@/api/SearchApi.js'
import CommonUtil from '@/utils/CommonUtil.js'

import store from '@/store';

const module = 'rss';
const list = ref([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const error = ref(false);
const errorText = ref('加载失败，请刷新重试');
const sitePicker = ref(false);
const searchForm = reactive({
  siteName: '',
  siteid: '',
  keyword: ''
});

const activeNames = ref(['1']);

const siteOptions = store.state.siteOptions;
const categoryOptions = store.state.categoryOptions;
const clientOptions = store.state.clientOptions;
const libraryOptions = store.state.libraryOptions;

const sitePickerOptions = siteOptions.map(item => {
  return {
    text: item.name,
    value: item.id,
    disabled: !item.rss
  }
});
const categoryFilterOptions = [
  {
    text: '全部',
    value: ''
  },
  ...categoryOptions.map(item => {
    return {
      text: item.name,
      value: item.folder
    }
  })
];

const categoryName = (value) => {
  return categoryOptions.find(item => item.folder === value)?.name
}

const sitePickerConfirm = (value) => {
  searchForm.siteid = value.value;
  searchForm.siteName = value.text;
  sitePicker.value = false;
}

// 筛选
const filter = reactive({
  category: ''
});
const filterList = ref([]);
watchEffect(() => {
  if (filter.category) {
    filterList.value = list.value.filter(item => item.category === filter.category)
  } else {
    filterList.value = list.value
  }
})

const onLoad = () => {
  SearchApi.rss(searchForm).then(response => {
    if (response.data.code === 1) {
      response.data.data.forEach(item => {
        list.value.push(item);
      });

      // 后台值只返回一次，所以没有下一页
      finished.value = true;
    } else {
      error.value = true;
      errorText.value = `数据加载失败：${response.data.message}`;
    }
  }).catch((error) => {
    error.value = true;
    errorText.value = `数据加载失败：${error.message}`;
  }).then(() => {
    loading.value = false;
  })
};

const onRefresh = () => {

  if (!searchForm.siteid) {
    Notify({ type: 'warning', message: '请选择站点' });
    return;
  }

  activeNames.value = [''];

  refreshing.value = false;

  // 清空列表数据
  filter.category = '';
  list.value = [];
  finished.value = false;

  error.value = false;
  errorText.value = '';
  // 重新加载数据
  // 将 loading 设置为 true，表示处于加载状态
  loading.value = true;

  onLoad();
};

//
const addTorrent = ref(null);
const addShow = ref(false);
let toAddRow = undefined;
const opShow = ref(false);
const actions = reactive([
  { name: '添加', disabled: false },
  { name: '跳转', color: 'green' },
]);
const opShowFunc = (item) => {
  toAddRow = {
    id: '',
    name: item.title,
    address: item.address,
    categoryid: item.category,
    link: item.link,
    hash: item.hash,
  };
  actions[0].disabled = item.isAdd;
  opShow.value = true;
}
const onSelect = (item, index) => {
  // 默认情况下点击选项时不会自动收起
  // console.log(index, item.name);
  if (index === 0) {
    addShow.value = true;
    nextTick(() => {
      addTorrent.value.initModel(toAddRow);
    })
  } else if (index === 1) {
    window.open(toAddRow.link);
  }
};

// init functions

</script>
<style scoped>

.row-title {}

.label-time {
  margin: 0;
  padding: 0;
}

.menu-btn {
  position: fixed;
  bottom: 20px;
  /* right: 20px; */
  width: 100%;
  text-align: right;
  padding-right: 20px;
}
</style>